/**
 * 
 */
package com.car.spdier.service.impl;

import java.io.IOException;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.httpclient.methods.PostMethod;
import org.htmlparser.Node;
import org.htmlparser.tags.TableColumn;
import org.htmlparser.tags.TableRow;
import org.htmlparser.tags.TableTag;
import org.htmlparser.util.ParserUtils;
import org.htmlparser.util.SimpleNodeIterator;

import com.car.file.FileUtil;
import com.car.spdier.HashTable;
import com.car.spdier.service.ParseService;
import com.car.spdier.service.dao.PunishmentDao;
import com.car.spdier.service.dao.entity.Punishment;
import com.car.spdier.service.dao.entity.SqlTable;
import com.car.spdier.service.dao.impl.PunishmentDaoImpl;
import com.comm.cache.CacheUtil;
import com.comm.cache.entity.CacheObject;
import com.comm.cache.entity.PunishmentObj;
import com.comm.cache.entity.Punishments;
import com.comm.cache.entity.QueryBase;
import com.comm.db.jdbc.JdbcUtil;
import com.spider.web.url.MyHttpClient;

/**
 * @author Administrator
 * 
 */
public abstract class BaseParseService implements ParseService {
	public static String charset = "gb2312";

	/**
	 * 
	 */
	public BaseParseService() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * 车牌号
	 */
	public Punishments parseRequest(final Map requestMap, QueryBase query) {

		if (query == null) {
			return null;
		}

		PostMethod postMethod = null;
		Punishments punishments = new Punishments();
		try {
			String cacheKey = query.getCacheKey();
			String cityCodeKey = query.getPunishmentCityCode();
			charset = HashTable.getCharset(cityCodeKey);
			/**
			 * 例如：处理 是不是重新从交警网站下载结果。 算法，如果最近30天有下载记录则从数据库取。如果最近10天没有下载记录，则下载 1.
			 * 从数据库中取 1.1 直接返回到前端 前期数据量不大，可以采用更快的方式：（数据量大时，采用采集入库，从库里取出放到缓存）
			 * 新设计：1.从cache中读取。(cache定时去更新,每周一，三，五晚上1点)
			 **/
			// 1. 直接返回到前端
			if (cacheKey != null) {
				CacheObject cacheObject = CacheUtil.getInstance().getContent(
						cacheKey.toString());
				if (cacheObject != null && cacheObject.isActive()) {
					return cacheObject.getPunishmentsByCity(cityCodeKey);
				}
			}

			// 2.从交警网站拉数据
			postMethod = MyHttpClient.getPostMethod(
					HashTable.getUrl(cityCodeKey), requestMap, charset);
			// 异步写文件
			FileUtil.write(postMethod.getResponseBodyAsStream(),
					FileUtil.getTargetDir(cacheKey + "/" + cityCodeKey));

			// 3 同步角析到返回前端
			ParseService parseService = ParseServiceFactory
					.getParseService(cityCodeKey);
			String responseBody = clean(postMethod.getResponseBodyAsString());
			punishments = parseService.parse(responseBody);
			// 4. 异步记录下载日志表，下载成功；5 .解析数据记录违章表。
			if (punishments.size() > 0) {
				stroeDb(punishments);
			}
			// 6. 同步设置 Cache
			setCache(cityCodeKey, punishments, query);
			return punishments;

		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
			System.out.print(e1.getStackTrace());
		}

		return punishments;

	}

	private void setCache(String cityCodeKey, Punishments punishments,
			QueryBase query) {
		CacheObject cacheObject = new CacheObject(query, punishments);
		CacheUtil.getInstance().putContent(cacheObject);
	}

	/**
	 * 去除String中多余的空格以及换行 1）去除换行 2）去除空格
	 * 
	 * @param str
	 * @return
	 */
	private String clean(String string) {
		// 去除换行
		Pattern pattern = Pattern.compile("[\\r\\n]{2,}");
		Matcher matcher = pattern.matcher(string);
		String result = matcher.replaceAll("\r\n");
		// 去除多余符号
		pattern = Pattern.compile(":{1,}|：{1,}");
		matcher = pattern.matcher(result);
		result = matcher.replaceAll("");
		// 去除多余空格
		pattern = Pattern.compile(" {2,}|\t{1,}|:|：");
		matcher = pattern.matcher(result);
		result = matcher.replaceAll(" ");

		return result;
	}

	protected Punishments parserTable(TableTag tableTag) {
		Punishments punishments = new Punishments();

		SimpleNodeIterator nodes = tableTag.elements();
		Punishment punishment = new Punishment();
		while (nodes.hasMoreNodes()) {
			Node node = nodes.nextNode();
			if (node instanceof TableRow) {
				TableRow row = (TableRow) node;
				System.out.println("--TableRow--处理开始---");

				SimpleNodeIterator colNodes = row.elements();
				while (colNodes.hasMoreNodes()) {
					Node colNode = colNodes.nextNode();
					if (colNode instanceof TableColumn) {
						TableColumn col = (TableColumn) colNode;
						String colText = ParserUtils.trimAllTags(
								col.getChildrenHTML(), false);
						colText = ParserUtils.removeEscapeCharacters(colText);
						colText = ParserUtils.removeTrailingBlanks(colText);
						colText = ParserUtils.removeChars(colText, ' ');
						if (punishment.isFull()) {
							punishments.add(punishment.toPunishmentObj());
							punishment = new Punishment();
						}
						punishment.setValue(colText);// 设置当前行值
						preprocePunishment(punishment, colText);// 设置下一行的标志

					}
				}
				System.out.println("--TableRow--处理结束---");
			}

		}
		return punishments;

	}

	/**
	 * 上海违章查询字段处理
	 * 
	 * @param prs
	 * @param colString
	 */
	protected void preprocePunishment(Punishment prs, String colString) {
		if (colString.startsWith("违法时间：")) {
			System.out.println(colString);
			prs.isRSDate = true;
			return;
		}
		if (colString.startsWith("编号：")) {
			System.out.println(colString);
			prs.isRS_code = true;
			return;
		}
		if (colString.startsWith("执法机关代码")) {
			System.out.println(colString);
			prs.isOrg_code = true;
			return;
		}
		if (colString.startsWith("违法地点：")) {
			System.out.println(colString);
			prs.isSpace = true;
			return;
		}
		if (colString.startsWith("采集机关：")) {
			System.out.println(colString);
			prs.isOrg_name = true;
			return;
		}
		if (colString.startsWith("违法内容：")) {
			System.out.println(colString);
			prs.isContent = true;
			return;
		}
		if (colString.startsWith("违反条款：")) {
			System.out.println(colString);
			prs.isClause = true;
			return;
		}
		if (colString.startsWith("处罚依据：")) {
			System.out.println(colString);
			prs.isAccord = true;
			return;
		}
		if (colString.startsWith("处罚内容：")) {
			System.out.println(colString);
			prs.isPunishment = true;
			return;
		}
		if (colString.startsWith("其他措施：")) {
			System.out.println(colString);
			prs.isPunishment = true;
			return;
		}

	}

	protected void stroeDb(Punishments punishments) {
		// 1.保存t_user_base_query
        
		// 2.
		storeTPunishment(punishments);
		// 3.保存关系表
		// 4.保存日志
	}
    
	protected void storeTPunishment(Punishments punishments) {
		List listQueryParams = null;
		List list = null;
		PunishmentDao dao = new PunishmentDaoImpl();
		for (PunishmentObj bean : punishments.getAll()) {
			System.out.println(bean.toString());
			if (dao.hasPunishmentByRsCode(bean.getRsCode())) {
				System.out.println("数据库下载了记录:" + bean.toString());
				return;
			} // 数据库下载了记录。
				// result_dt, org_code, rs_code, rs_space, org_name, content,
				// clause, accord, Punishment, PunishmentOther
			dao.stroeTPunishment(bean);
			listQueryParams = new ArrayList();

		}
		// JdbcUtil.GetJdbc().excuteBathe(SqlTable.INSERT_TPUNISHMENT ,
		// listObjs);

	}
    
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
